package com.dd.cloud.common.utils;

import com.dd.cloud.common.annotate.StatusId;
import com.dd.cloud.common.constants.RegularConstants;
import com.dd.cloud.common.enums.ZkExceptionEnum;
import com.dd.cloud.common.exception.ZekeException;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.regex.Matcher;

/**
 * 正则工具类
 *
 * @author Lx
 * @version 1.0
 */
public class Assert {
    /**
     * 验证(状态,id..)多选参数合法性
     *
     * @param param     参数
     * @param paramName 参数名
     * @param required  是否必传参数
     */
    public static void verifyStatusIdsParam(String param, String paramName, boolean required) {
        boolean flag = required && StringUtils.isBlank(param);
        if (!flag && !StringUtils.isBlank(param)) {
            Matcher matcher = RegularConstants.STATUS_ID_REGEXP.matcher(param);
            flag = !matcher.matches();
        }
        if (flag) {
            if (paramName != null) {
                throw new ZekeException(ZkExceptionEnum.PARAM_DATA_ERROR.getCode(), paramName + ":" + ZkExceptionEnum.PARAM_DATA_ERROR.getMsg());
            }
            throw new ZekeException(ZkExceptionEnum.PARAM_DATA_ERROR);
        }
    }

    /**
     * 验证(状态,id..)多选参数合法性
     *
     * @param cls 对象
     */
    public static <T> void verifyStatusIdsParam(Class<?> cls, T t) {
        Field[] fields = cls.getDeclaredFields();
        for (Field item : fields) {
            StatusId statusId = item.getAnnotation(StatusId.class);
            if (statusId != null && item.getType() == String.class) {
                String paramName = statusId.name();
                if ("".equals(paramName)) {
                    paramName = item.getName();
                }
                try {
                    item.setAccessible(true);
                    Object obj = item.get(t);
                    verifyStatusIdsParam(obj == null ? null : obj.toString(), paramName, statusId.required());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
